﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.Transactions;

using MINERP.BLL.Statistics;
using MINERP.DAL;
using MINERP.MODEL.Statistics;
using MINERP.MODEL.FoundationModel;
using MINERP.COM;
using MINERP.ComControls;
using FastReport;
using FastReport.Editor;
using System.IO;

namespace MINERP.Statistics
{

    public partial class FrmPay : Form
    {
        private static FrmPay instance = null;
        public static int shopid;
        public static FrmFinance frmFinance = null;
        FinanceBLL _bll = new FinanceBLL();
        private MINERP.MODEL.FoundationModel.Shop_Info _shop = null;
        private orderInfo _orderInfo = null;
        private decimal creditLimit = 0;    // 信用额
        private decimal orderBlance = 0;     // 产品订单余额

        private decimal _blance = 0;         // 帐户余额
        public decimal blance { get { return _blance; } set { _blance = value; CanCheckOutMoney = (double)value + _arrearageCount; } }// 帐户余额



        private double _CanCheckOutMoney = 0;//能够抵冲的金额
        public double CanCheckOutMoney { get { return _CanCheckOutMoney; } set { _CanCheckOutMoney = value; lblCanCheckOutMoney.Text = _CanCheckOutMoney.ToString("0.00"); } }

        private double _arrearageCount;//欠款总额
        public double ArrearageCount { get { return _arrearageCount; } set { _arrearageCount = value; CanCheckOutMoney = value + (double)_blance; txtAllNeedPayBill.Text = _arrearageCount.ToString("0.00"); } }


        private decimal _allBillCount;      //将要抵冲的金额
        public decimal allBillCount { get { return _allBillCount; } set { _allBillCount = value; txtAllBillMoney.Text = value.ToString("0.00"); } }

        private FrmPay()
        {
            InitializeComponent();
        }

        public static FrmPay GetInstance
        {
            get
            {
                if (instance == null)
                {
                    instance = new FrmPay();
                }
                return instance;
            }

        }
        private void FrmPay_Load(object sender, EventArgs e)
        {
            txtClearMoney.Text = "0";
            _shop = _bll.GetShopObj(shopid);
            if (_shop.CheckOutType == (int)CheckOutType.FirstCheckOut)
            {
                gridControlBill.Visible = false;
                gridControlOrderBag.Visible = true;
            }
            else
            {
                gridControlOrderBag.Visible = false;
                gridControlBill.Visible = true;

                gridControlBill.DataSource = _bll.GetBillList(_shop);
                CountAllBillNeedPay();
            }
            RefreshStatus();
            LinkShops();
            cmbShop.Text = _shop.ShopName;
            comboBoxPayType.SelectedIndex = 0;
        }
        private void FrmPay_FormClosed(object sender, FormClosedEventArgs e)
        {
            instance = null;
        }

        public void RefreshStatus()
        {

            if (_shop.OrderBalance != null)
            {
                orderBlance = Math.Round((decimal)_shop.OrderBalance, 2);
            }
            if (_shop.Balance != null)
            {
                blance = Math.Round((decimal)_shop.Balance, 2);
            }
            if (_shop.CreditLimit != null)
            {
                creditLimit = Math.Round((decimal)_shop.CreditLimit);
            }

            switch (_shop.CheckOutType)
            {
                case 0:
                    tssCheckOutType.Text = "预付款";
                    break;
                case 1:
                    tssCheckOutType.Text = "信用额度";
                    tssCreditLimit.Visible = true;
                    tssCreditLimitLabel.Visible = true;
                    tssCreditLimitUnit.Visible = true;
                    break;
                case 2:
                    tssCheckOutType.Text = "现结";
                    break;
                case 3:
                    tssCheckOutType.Text = "结账日期";
                    break;
                case 4:
                    tssCheckOutType.Text = "结账日期与信用额度";
                    tssCreditLimit.Visible = true;
                    tssCreditLimitLabel.Visible = true;
                    tssCreditLimitUnit.Visible = true;
                    break;
                case 5:
                    tssCheckOutType.Text = "先结";
                    break;
                default:
                    break;
            }

            tssShop.Text = _shop.ShopName;
            tssOrderBlance.Text = orderBlance.ToString();
            tssBlance.Text = blance.ToString();
            tssCreditLimit.Text = creditLimit.ToString();

        }
        private void btnOk_Click(object sender, EventArgs e)
        {
            if (txtMoney.Text != string.Empty && Convert.ToDecimal(txtMoney.Text) != 0)
            {
                if (DialogResult.OK == MessageBox.Show("确定冲值" + txtMoney.Text + "元吗？", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question))
                {
                    using (newSampleYPDBEntities db=new newSampleYPDBEntities ())
                    {
                        if (db.Connection.State != System.Data.ConnectionState.Open)
                        {
                            db.Connection.Open();
                        }
                        string CrushType = "";
                        using (System.Data.Common.DbTransaction tran = db.Connection.BeginTransaction(System.Data.IsolationLevel.ReadCommitted))
                        {
                            try
                            {
                                Shop curShop = db.Shop.FirstOrDefault(s => s.ShopId == _shop.ShopId);
                                if (curShop != null)
                                {
                                    if (curShop.Balance != null)
                                    {
                                        curShop.Balance += Math.Round(Convert.ToDecimal(txtMoney.Text), 2);
                                    }
                                    else
                                    {
                                        curShop.Balance = Math.Round(Convert.ToDecimal(txtMoney.Text), 2);
                                    }

                                    _shop.Balance = (decimal)curShop.Balance;
                                    db.SaveChanges();
                                }

                                //插入充值记录
                                string strRemark = "充值";
                                if (!string.IsNullOrEmpty(txtRemark.Text.Trim()))
                                {
                                    strRemark = txtRemark.Text.Trim();
                                }
                                
                                ShopBlanceCrushRecord crushRecord = new ShopBlanceCrushRecord();
                                crushRecord.CrushMoney = Convert.ToDecimal(txtMoney.Text);
                                crushRecord.CrushTime = DateTime.Now;
                                crushRecord.Operator = FrmMain.loginName;
                                Shop currShop = db.Shop.FirstOrDefault(shop => shop.ShopId == _shop.ShopId);
                                crushRecord.Shop = currShop;
                                crushRecord.Remark = strRemark;
                                crushRecord.Overage = (decimal)currShop.Balance;
                                if (comboBoxPayType.SelectedIndex == 0)
                                {
                                    crushRecord.Operation = (int)CountOperationType.ChongZhi;
                                    CrushType = "充值";
                                }
                                else
                                {
                                    crushRecord.Operation = (int)CountOperationType.QingLing;
                                    CrushType = "优惠或抹零";
                                }
                                db.SaveChanges();
                                tran.Commit();
                                if (checkBoxIsPrint.Checked)
                                {
                                    PrintCrushBill(crushRecord.CrushMoney, crushRecord.Overage, crushRecord.Operator, crushRecord.CrushTime, crushRecord.Shop.shopName, crushRecord.Remark, CrushType);
                                }
                            }
                            catch (Exception ex)
                            {
                                tran.Rollback();
                                throw ex;
                            }
                        }
                        
                    }

                    

                    //CrushRecord(strRemark, Convert.ToDecimal(txtMoney.Text), CountOperationType.ChongZhi);
                    //自动激活那些因为欠款而不能生产的产品
                    _bll.ActiveOrder(_shop);

                    RefreshStatus();
                    frmFinance.LinkDataGrid();
                    txtMoney.Text = string.Empty;
                    MessageBox.Show("充值成功,充值金额：" + txtMoney.Text+" 元", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            else
            {
                MessageBox.Show("请输入充值金额", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                txtMoney.Focus();
            }
        }
        private void PrintCrushBill(decimal crushMoney, decimal overage, string oprator, DateTime crushtime, string shopName, string remark, string CrushType)
        {
            Report rpt = new Report();
            rpt.Load(Application.StartupPath + "\\Report\\CrushBill.frx");
            rpt.SetParameterValue("ShopName", shopName);
            rpt.SetParameterValue("CrushMoney",crushMoney);
            rpt.SetParameterValue("Overage",overage);
            rpt.SetParameterValue("CrushTime", crushtime);
            rpt.SetParameterValue("Oprator", oprator);
            rpt.SetParameterValue("Remark", remark);
            rpt.SetParameterValue("CrushType", remark);
            rpt.SetParameterValue("CrushType", CrushType);
            rpt.PrintSettings.ShowDialog = true;
            rpt.Print();
            rpt.Prepare();
            string excelPath = Application.StartupPath + "\\报表文件\\" + shopName;
            if (!Directory.Exists(excelPath))
            {
                Directory.CreateDirectory(excelPath);
            }
            string repPath = excelPath + "\\" + DateTime.Now.ToString().Replace(":", " ") + ".fpx";
            rpt.SavePrepared(repPath);
        }
        private void gridViewProductOrder_CellValueChanging(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            BillEntity billEntity = (BillEntity)gridViewBill.GetRow(e.RowHandle);
            if ((bool)e.Value)
            {
                ////////allBillCount += (decimal)billEntity.BillCount;
                ////////allBillCount = Math.Round(allBillCount, 2);
                /////////if (allBillCount <= _shop.Balance + (txtClearMoney.Text == null ? 0 : Convert.ToDecimal(txtClearMoney.Text)))
                //if ((double)allBillCount + billEntity.NoPayBillCount <= CanCheckOutMoney + (txtClearMoney.Text == null ? 0 : Convert.ToDouble(txtClearMoney.Text)))
                //{
                    allBillCount += (decimal)billEntity.NoPayBillCount;
                    //txtAllBillMoney.Text = Math.Round(allBillCount, 2).ToString();
                //}
                //else
                //{
                //    billEntity.IsChecked = false;
                //    gridViewBill.RefreshData();
                //    //////////allBillCount -= (decimal)billEntity.BillCount;
                //    //////////txtAllBillMoney.Text = Math.Round(allBillCount, 2).ToString();
                //    MessageBox.Show("可抵冲余额不足", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

                //}
            }
            else
            {
                allBillCount -= (decimal)billEntity.NoPayBillCount;
                //txtAllBillMoney.Text = Math.Round(allBillCount, 2).ToString();
            }
        }

        private void btnActiveOrder_Click(object sender, EventArgs e)
        {
            if (txtAllBillMoney.Text == string.Empty || !isAnyChecked())
            {
                MessageBox.Show("请选择要冲抵的账单！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            decimal money = allBillCount - Convert.ToDecimal(txtClearMoney.Text);//实际冲抵金额 
            if (DialogResult.OK == MessageBox.Show("确定冲抵以下选中帐单吗？", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question))
            {
                //bool active = true;
                //if (!_shop.SHOP_Bill.IsLoaded)
                //{
                //    _shop.SHOP_Bill.Load();
                //}
                //List<SHOP_Bill> listBill = _shop.SHOP_Bill.ToList();
                DateTime dt = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);

                List<BillEntity> selectedBill = ((List<BillEntity>)gridViewBill.DataSource).Where(b => b.IsChecked).ToList();
                if (selectedBill.Count<1)
                {
                    return;
                }

                using (newSampleYPDBEntities db = new newSampleYPDBEntities())
                {
                    foreach (var billInfo in selectedBill)
                    {
                        SHOP_Bill bill = db.SHOP_Bill.FirstOrDefault(b => b.BillId == billInfo.BillID);
                        bill.Status = (int)ShopBillStatus.CheckedOut;
                        bill.checkOutTime = DateTime.Now;
                        
                        if (!bill.Bill_Detail.IsLoaded)
                        {
                            bill.Bill_Detail.Load();
                        }
                        foreach (var billDetail in bill.Bill_Detail)
                        {
                            billDetail.IsCheckOut = true;
                        }
                    }

                    CrushRecord("冲抵账单", -money, CountOperationType.DiChong);
                    if (txtClearMoney.Text != string.Empty && Convert.ToDecimal(txtClearMoney.Text) != 0)
                    {
                        CrushRecord("清零(" + txtClearRemark.Text + ")", -Convert.ToDecimal(txtClearMoney.Text), CountOperationType.QingLing);
                    }
                    db.SaveChanges();
                }

                #region 激活相应的产品
                switch ((CheckOutType)_shop.CheckOutType)
                {
                        //预付款
                    case CheckOutType.PrePay:
                        break;
                        //信用额度
                    case CheckOutType.CreditLimit:
                        break;
                        //现结用户
                    case CheckOutType.CheckOutNow:
                        break;
                        //结帐日期
                    case CheckOutType.DateTimeCheckOut:
                        break;
                        //信用额度与结账日期
                    case CheckOutType.CreditLimitAndDateTime:
                        break;
                        //先结
                    case CheckOutType.FirstCheckOut:
                        break;
                        //代收
                    case CheckOutType.DelegateCheckOut:
                        break;
                    default:
                        break;
                }
                #endregion

                #region 注释
                /*
                switch (_shop.CheckOutType)
                {
                    case 0://预付款商户
  
                        break;

                    case 1://信用额商户
                        for (int i = 0; i < gridViewBill.RowCount; i++)
                        {
                            BillEntity billEntity = (BillEntity)gridViewBill.GetRow(i);
                            if (billEntity.IsChecked)
                            {
                                SHOP_Bill bill = _bll.GetBillObj(billEntity.BillID);
                                bill.Status = (int)ShopBillStatus.CheckedOut;
                                //_shop.Balance -= (decimal)billEntity.BillCount;
                                //_shop.OrderBalance += (decimal)billEntity.BillCount;
                                _bll.Update();
                                //RefreshStatus();
                            }
                        }
                        _shop.Balance -= money;
                        _shop.OrderBalance += money;

                        List<OrderProductEntity> list = new List<OrderProductEntity>();
                        list = _bll.GetOrderProductList(_shop.ShopId);
                        list.Sort(delegate(OrderProductEntity s1, OrderProductEntity s2) { return s1.StartOrderTime.CompareTo(s2.StartOrderTime); });
                        for (int i = 0; i < list.Count; i++)
                        {
                            _orderInfo = _bll.GetOrderInfoObj(list[i].OrderProductId);
                            if (_shop.OrderBalance >= list[i].PrePriceCount)
                            {
                                _orderInfo.status = (int)OrderInfoStatus.Doing;
                                _shop.OrderBalance -= _orderInfo.PrePriceCount == null ? 0 : _orderInfo.PrePriceCount;
                                _bll.Update();
                                //RefreshStatus();
                            }

                        }
                        CrushRecord("冲抵账单", -money, OperationType.DiChong);
                        if (txtClearMoney.Text != string.Empty && Convert.ToDecimal(txtClearMoney.Text) != 0)
                        {
                            CrushRecord("清零(" + txtClearRemark.Text + ")", -Convert.ToDecimal(txtClearMoney.Text), OperationType.QingLing);
                        }
                        break;
                    case 2://现结商户
                        for (int i = 0; i < gridViewBill.RowCount; i++)
                        {
                            BillEntity billEntity = (BillEntity)gridViewBill.GetRow(i);
                            if (billEntity.IsChecked)
                            {
                                SHOP_Bill bill = _bll.GetBillObj(billEntity.BillID);
                                bill.Status = (int)ShopBillStatus.CheckedOut;
                                //_shop.Balance -= (decimal)billEntity.BillCount;
                                _bll.Update();
                                //RefreshStatus();
                            }
                        }

                        _shop.Balance -= money;

                        List<OrderProductEntity> list1 = new List<OrderProductEntity>();
                        list1 = _bll.GetOrderProductList(_shop.ShopId);
                        list1.Sort(delegate(OrderProductEntity s1, OrderProductEntity s2) { return s1.StartOrderTime.CompareTo(s2.StartOrderTime); });
                        for (int i = 0; i < list1.Count; i++)
                        {
                            _orderInfo = _bll.GetOrderInfoObj(list1[i].OrderProductId);
                            _orderInfo.status = (int)OrderInfoStatus.Doing;
                            _bll.Update();
                            //RefreshStatus();
                        }
                        CrushRecord("冲抵账单", -money, OperationType.DiChong);
                        if (txtClearMoney.Text != string.Empty && Convert.ToDecimal(txtClearMoney.Text) != 0)
                        {
                            CrushRecord("清零(" + txtClearRemark.Text + ")", Convert.ToDecimal(txtClearMoney.Text), OperationType.QingLing);
                        }
                        break;
                    case 3://结账日期商户

                        for (int i = 0; i < gridViewBill.RowCount; i++)
                        {
                            BillEntity billEntity = (BillEntity)gridViewBill.GetRow(i);
                            if (billEntity.IsChecked)
                            {
                                SHOP_Bill bill = _bll.GetBillObj(billEntity.BillID);
                                bill.Status = (int)ShopBillStatus.CheckedOut;
                                //_shop.Balance -= (decimal)billEntity.BillCount;
                                _bll.Update();
                                //RefreshStatus();
                            }
                        }
                        _shop.Balance -= money;
                        foreach (var item in listBill)
                        {
                            if (item.CreateTime < dt && item.Status == (int)ShopBillStatus.UnCheckOut)
                            {
                                active = false;
                                break;
                            }
                        }
                        if (active)
                        {
                            List<OrderProductEntity> list2 = new List<OrderProductEntity>();
                            list2 = _bll.GetOrderProductList(_shop.ShopId);
                            list2.Sort(delegate(OrderProductEntity s1, OrderProductEntity s2) { return s1.StartOrderTime.CompareTo(s2.StartOrderTime); });
                            for (int i = 0; i < list2.Count; i++)
                            {
                                _orderInfo = _bll.GetOrderInfoObj(list2[i].OrderProductId);
                                _orderInfo.status = (int)OrderInfoStatus.Doing;
                                _bll.Update();
                                //RefreshStatus();
                            }
                        }
                        CrushRecord("冲抵账单", -money, OperationType.DiChong);
                        if (txtClearMoney.Text != string.Empty && Convert.ToDecimal(txtClearMoney.Text) != 0)
                        {
                            CrushRecord("清零(" + txtClearRemark.Text + ")", -Convert.ToDecimal(txtClearMoney.Text), OperationType.QingLing);
                        }
                        break;
                    case 4://结账日期与信用额
                        for (int i = 0; i < gridViewBill.RowCount; i++)
                        {
                            BillEntity billEntity = (BillEntity)gridViewBill.GetRow(i);
                            if (billEntity.IsChecked)
                            {
                                SHOP_Bill bill = _bll.GetBillObj(billEntity.BillID);
                                bill.Status = (int)ShopBillStatus.CheckedOut;
                                //_shop.Balance -= (decimal)billEntity.BillCount;
                                //_shop.OrderBalance += (decimal)billEntity.BillCount;
                                _bll.Update();
                                //RefreshStatus();
                            }
                        }
                        _shop.Balance -= money;
                        _shop.OrderBalance += money;

                        foreach (var item in listBill)
                        {
                            if (item.CreateTime < dt && item.Status == (int)ShopBillStatus.UnCheckOut)
                            {
                                active = false;
                                break;
                            }
                        }
                        if (active)
                        {
                            List<OrderProductEntity> list3 = new List<OrderProductEntity>();
                            list3 = _bll.GetOrderProductList(_shop.ShopId);
                            list3.Sort(delegate(OrderProductEntity s1, OrderProductEntity s2) { return s1.StartOrderTime.CompareTo(s2.StartOrderTime); });
                            for (int i = 0; i < list3.Count; i++)
                            {
                                _orderInfo = _bll.GetOrderInfoObj(list3[i].OrderProductId);
                                if (_shop.OrderBalance >= list3[i].PrePriceCount)
                                {
                                    _orderInfo.status = (int)OrderInfoStatus.Doing;
                                    _shop.OrderBalance -= _orderInfo.PrePriceCount == null ? 0 : _orderInfo.PrePriceCount;
                                    _bll.Update();
                                    //RefreshStatus();
                                }
                            }
                        }
                        CrushRecord("冲抵账单", -money, OperationType.DiChong);
                        if (txtClearMoney.Text != string.Empty && Convert.ToDecimal(txtClearMoney.Text) != 0)
                        {
                            CrushRecord("清零(" + txtClearRemark.Text + ")", -Convert.ToDecimal(txtClearMoney.Text), OperationType.QingLing);
                        }
                        break;
                    default:
                        break;
                }*/
#endregion

                RefreshStatus();
                
                gridControlBill.DataSource = _bll.GetBillList(_shop);
                frmFinance.LinkDataGrid();
                CountAllBillNeedPay();
                allBillCount = 0;
                txtAllBillMoney.Text = string.Empty;
                txtClearMoney.Text = "0";
            }
        }

        private void tsbtnSelectAll_Click(object sender, EventArgs e)
        {
            allBillCount = 0;
            for (int i = 0; i < gridViewBill.RowCount; i++)
            {
                BillEntity billEntity = (BillEntity)gridViewBill.GetRow(i);
                allBillCount += (decimal)billEntity.NoPayBillCount;
            }
            if (CanCheckOutMoney >= (double)allBillCount)
            {
                allBillCount = 0;
                for (int i = 0; i < gridViewBill.RowCount; i++)
                {
                    BillEntity billEntity = (BillEntity)gridViewBill.GetRow(i);
                    billEntity.IsChecked = true;
                    allBillCount += (decimal)billEntity.NoPayBillCount;
                }
                txtAllBillMoney.Text = Math.Round(allBillCount, 2).ToString();
                gridViewBill.RefreshData();
            }
            else
            {
                allBillCount = 0;
                MessageBox.Show("帐户余额不足,不能全选，请逐条选择！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
        public void LinkShops()
        {
            foreach (var item in _bll.GetShops())
            {
                cmbShop.Properties.Items.Add(item.shopName.ToString());
            }
        }

        private void cmbShop_Closed(object sender, DevExpress.XtraEditors.Controls.ClosedEventArgs e)
        {
            _shop = _bll.GetShopObj(cmbShop.Text);
            RefreshStatus();
            gridControlBill.DataSource = _bll.GetBillList(_shop);
            gridViewBill.RefreshData();
            CountAllBillNeedPay();

        }
        private void CountAllBillNeedPay()
        {
            double AllBillNeedPay = 0;
            for (int i = 0; i < gridViewBill.RowCount; i++)
            {
                BillEntity billEntity = new BillEntity();
                billEntity = (BillEntity)gridViewBill.GetRow(i);
                AllBillNeedPay += billEntity.NoPayBillCount;
            }
            //CanCheckOutMoney = (double)blance + AllBillNeedPay;
            ArrearageCount = AllBillNeedPay;
            //lblCanCheckOutMoney.Text = Math.Round(blance + (decimal)AllBillNeedPay, 2).ToString();
            //txtAllNeedPayBill.Text = Math.Round(AllBillNeedPay, 2).ToString();
        }

        private void CrushRecord(string type, decimal money, CountOperationType OperationType)
        {
            //ShopBlanceCrushRecord crushRecord = new ShopBlanceCrushRecord();
            //crushRecord.CrushMoney = money;
            //crushRecord.CrushTime = DateTime.Now;
            //crushRecord.Operator = FrmMain.loginName;
            //crushRecord.Shop = _shop;
            ////if (OperationType.DiChong == OperationType || OperationType.QingLing == OperationType)
            ////{
            ////    ShopBlanceCrushRecord lastSB;
            ////    //using (newSampleYPDBEntities DB = new newSampleYPDBEntities())
            ////    //{
            ////    //    //lastSB = DB.ShopBlanceCrushRecord.Where(b => b.Shop.ShopId == _shop.ShopId && (b.Operation == 1 || b.Operation == 2)).OrderByDescending(b => b.CrushTime).FirstOrDefault();
            ////    //    lastSB = DB.ShopBlanceCrushRecord.Where(b => b.Shop.ShopId == _shop.ShopId).OrderByDescending(b => b.CrushTime).FirstOrDefault();
            ////    //}
            ////    //if (lastSB == null)//还未有相应记的记录
            ////    //{
            ////    //    //crushRecord.Overage = (decimal)_shop.Balance + money;
            ////    //}
            ////    //else
            ////    //{
            ////    //    crushRecord.Overage = lastSB.Overage + money;
            ////    //}
            ////}
            ////else
            ////{
            //    crushRecord.Overage = (decimal)_shop.Balance;
            ////}

            //crushRecord.Remark = type;
            //crushRecord.Operation = (int)OperationType;
            //_bll.Update();
            using (newSampleYPDBEntities db = new newSampleYPDBEntities())
            {
                ShopBlanceCrushRecord crushRecord = new ShopBlanceCrushRecord();
                crushRecord.CrushMoney = money;
                crushRecord.CrushTime = DateTime.Now;
                crushRecord.Operator = FrmMain.loginName;
                Shop currShop = db.Shop.FirstOrDefault(shop => shop.ShopId == _shop.ShopId);
                crushRecord.Shop = currShop;
                crushRecord.Remark = type;
                crushRecord.Overage = (decimal)currShop.Balance;
                crushRecord.Operation = (int)OperationType;
                db.SaveChanges();
            }
        }

        private void tsbtnFanXuan_Click(object sender, EventArgs e)
        {
            allBillCount = 0;
            List<BillEntity> list = new List<BillEntity>();
            for (int i = 0; i < gridViewBill.RowCount; i++)
            {
                BillEntity billEntity = (BillEntity)gridViewBill.GetRow(i);
                if (!billEntity.IsChecked)
                {
                    allBillCount += (decimal)billEntity.NoPayBillCount;
                }

            }
            if (CanCheckOutMoney >= (double)allBillCount)
            {
                allBillCount = 0;
                for (int i = 0; i < gridViewBill.RowCount; i++)
                {
                    BillEntity billEntity = (BillEntity)gridViewBill.GetRow(i);
                    if (!billEntity.IsChecked)
                    {
                        billEntity.IsChecked = true;
                        list.Add(billEntity);
                        allBillCount += (decimal)billEntity.NoPayBillCount;
                    }
                    else
                    {
                        billEntity.IsChecked = false;
                        list.Add(billEntity);
                    }
                }
                txtAllBillMoney.Text = Math.Round(allBillCount, 2).ToString();
                gridControlBill.DataSource = list;
            }
            else
            {
                allBillCount = 0;
                MessageBox.Show("帐户余额不足,不能反选，请逐条选择！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private bool isAnyChecked()
        {
            bool flag = false;
            for (int i = 0; i < gridViewBill.RowCount; i++)
            {
                BillEntity billEntity = (BillEntity)gridViewBill.GetRow(i);
                if (billEntity.IsChecked)
                {
                    flag = true;
                    break;
                }
            }
            return flag;
        }

        //根据可抵冲金额选择适当的帐单
        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            allBillCount = 0;
            for (int i = 0; i < gridViewBill.RowCount; i++)
            {
                BillEntity billEntity = (BillEntity)gridViewBill.GetRow(i);
                if ((decimal)CanCheckOutMoney>=(allBillCount+(decimal)billEntity.NoPayBillCount))//可抵冲
                {
                    allBillCount += (decimal)billEntity.NoPayBillCount;
                    billEntity.IsChecked = true;
                }                
            }

            gridViewBill.RefreshData(); 
        }
    }
}
